/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.user.client;

import com.cleangwt.user.client.AnchorActionEvent.AnchorActionHandler;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;

/**
 * Represents a anchor action event. This event is friendly to anchor element, to represent an
 * action event, the element may just like &lt;a href='#@theAction1'&gt; or &lt;a
 * href='#@theAction2/param1/param2'&gt;, make the href with ACTION_PREFIX '@' and follwing action
 * name and parameters(optional) that should be concated with PRRAM_DELIMETER '/', finally reigsiter
 * {@link ClickHandler} for the anchor element and invoke
 * {@link #translate(HasAnchorActionHandlers, ClickEvent)} to convert click event to an anchor event
 * with the action name and parameters that parsed from href of anchor element.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class AnchorActionEvent extends GwtEvent<AnchorActionHandler> {
  /**
   * Handler interface for {@link AnchorActionEvent} events.
   */
  public interface AnchorActionHandler extends EventHandler {
    /**
     * Called when a {@link AnchorActionEvent} is fired.
     * 
     * @param event the {@link AnchorActionEvent} that was fired
     */
    void onAnchorAction(AnchorActionEvent event);
  }

  /**
   * Interface specifying that a class can add {@code ActionHandler}s.
   */
  public interface HasAnchorActionHandlers extends HasHandlers {
    /**
     * Adds a {@link AnchorActionEvent} handler.
     * 
     * @param handler the handler
     * @return {@link HandlerRegistration} used to remove this handler
     */
    HandlerRegistration addAnchorActionHandler(AnchorActionHandler handler);
  }

  /**
   * Handler type.
   */
  private static Type<AnchorActionHandler> TYPE;

  /**
   * Fires an action event on all registered handlers in the handler manager. If no such handlers
   * exist or no specified process for the action, it will do nothing.
   * 
   * @param source the source
   * @param event the action action
   */
  public static <T> void fire(HasAnchorActionHandlers source, AnchorActionEvent event) {
    if (TYPE != null) {
      event.setSource(source);
      source.fireEvent(event);
    }
  }

  /**
   * Fires {@link AnchorActionEvent} if any anchor link(with {@link #ACTION_HASH_PREFIX}) of the
   * given target is clicked.
   * 
   * @param target the target
   * @param event the click event
   */
  public static void translate(HasAnchorActionHandlers target, ClickEvent event) {
    Element e = event.getNativeEvent().getEventTarget().cast();
    if (e.getTagName().equalsIgnoreCase(AnchorElement.TAG)) {
      if (HashTokenizer.isActionHash(e.getAttribute("href"))) {
        event.preventDefault();
        AnchorActionEvent.fire(target, e.getAttribute("href").substring(1));
      }
    }
  }

  /**
   * Fires an anchor action event on all registered handlers in the handler manager. If no such
   * handlers exist or no specified process for the action, it will do nothing.
   * 
   * @param source the source of the handlers
   * @param hashToken the hash
   */
  public static <T> void fire(HasAnchorActionHandlers source, String hashToken) {
    String action = HashTokenizer.parseIdentifier(hashToken);
    String[] params = HashTokenizer.parseHashParams(hashToken);
    fire(source, new AnchorActionEvent(action, params));
  }

  /**
   * Fires an action event on all registered handlers in the handler manager. If no such handlers
   * exist or no specified process for the action, it will do nothing.
   * 
   * @param source the source of the handlers
   * @param action the action
   * @param params the params
   */
  public static <T> void fire(HasAnchorActionHandlers source, String action, String[] params) {
    fire(source, new AnchorActionEvent(action, params));
  }

  /**
   * Gets the type associated with this event.
   * 
   * @return returns the handler type
   */
  public static Type<AnchorActionHandler> getType() {
    if (TYPE == null) {
      TYPE = new Type<AnchorActionHandler>();
    }
    return TYPE;
  }

  private final String action;
  private final String[] parameters;

  /**
   * Creates a action event.
   * 
   * @param action
   */
  protected AnchorActionEvent(String action, String[] params) {
    assert action != null;
    this.action = action;
    this.parameters = params;
  }

  @Override
  protected void dispatch(AnchorActionHandler handler) {
    handler.onAnchorAction(this);
  }

  /**
   * @return the action
   */
  public String getAction() {
    return action;
  }

  /**
   * Gets the type associated with this event.
   * 
   * @return returns the handler type
   */
  @Override
  public Type<AnchorActionHandler> getAssociatedType() {
    return AnchorActionEvent.TYPE;
  }

  /**
   * Gets the parameters.
   * 
   * @return the parameters
   */
  public String[] getParameters() {
    return parameters;
  }

}
